package com.designschool.base.http;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity; 
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.SyncBasicHttpContext;

import com.designschool.base.download.Downloader;
import com.designschool.base.notice.DownloadListener;
import com.designschool.base.notice.HttpRequestListener;

import android.content.Context;
import android.util.Log;

/****
 * 
 * @User   :shibaotong
 * @创建时间 :2013-10-27
 * @描述    :请求方式
 */
public class HttpClient {

	private static final int SOCKETTIMEOUT=5*1000;
	private HttpContext httpContext;
	private final DefaultHttpClient httpClient;
	private static final int MAXCONNECTIONS=5;
	private static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
	private static final String VERSION = "1.4.3";
	private static String encoding="UTF-8";
	
	private Map<String, String> headers;
	
	/***
	 * 构建方法初始化数据
	 */
	public HttpClient(){
		  BasicHttpParams httpParams = new BasicHttpParams();
	        /* 从连接池中取连接的超时时间 */
	        ConnManagerParams.setTimeout(httpParams, SOCKETTIMEOUT);
	        /*设置路由连接次数*/
	        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(MAXCONNECTIONS));
	        /*最大连接次数*/
	        ConnManagerParams.setMaxTotalConnections(httpParams, MAXCONNECTIONS);
	        
	        /* 请求超时 */
	        HttpConnectionParams.setSoTimeout(httpParams, SOCKETTIMEOUT);
	        /* 连接超时 */
	        HttpConnectionParams.setConnectionTimeout(httpParams, SOCKETTIMEOUT);
	        HttpConnectionParams.setTcpNoDelay(httpParams, true);
	        HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

	        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
	        HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

	        SchemeRegistry schemeRegistry = new SchemeRegistry();
	        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
	        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
	        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

	        httpContext = new SyncBasicHttpContext(new BasicHttpContext());
	        httpClient = new DefaultHttpClient(cm, httpParams);
	        
	        /***
	         * 初始化头信息
	         */
	        headers=new HashMap<String, String>();
	}
	
	/***
	 * 增加头信息
	 */
	public void addHeader(String header, String value){
	    headers.put(header, value);
	}
	
	
	
	/***
	 * 清空头信息
	 */
	public void clearHeader(){
	    headers.clear();
	}
	
	/***
	 * 设置请求编码
	 * @param encoding
	 */
	public void setEncoding(String encoding)
	{
		this.encoding=encoding;
	}
	
	/***
	 * get请求
	 * @param url 请求网址
	 * @param Httpparamname 接口名称用于一个界面同时多个请求判断属于那个接口返回的数据
	 * @param params 请求参数
	 * @param RequestListener 回调接口
	 * @param contentType 请求类型 比如 （application/json ）一般没有请求类型传个null值
	 */
	public void get(String url , String requestname , HttpRequestParams params ,HttpRequestListener RequestListener,String contentType ,boolean recordbool)
	{
		if(url==null)
			return;
		if(params==null)
			params=new HttpRequestParams();
		
		sendRequest(httpClient,httpContext,new HttpGet(getUrlString(url, params)),requestname,RequestListener,contentType,recordbool);
	}
	
	/***
	 * post 请求方式
	 * @param url
	 * @param requestname
	 * @param params
	 * @param RequestListener
	 * @param contentType
	 */
	public void post(String url , String requestname , HttpRequestParams params ,HttpRequestListener RequestListener,String contentType,boolean recordbool)
	{
		if(url==null)
			return;
		if(params==null)
			params=new HttpRequestParams();
		
		sendRequest(httpClient,httpContext,addEntityToRequestBase(new HttpPost(url),params.getEntity(encoding)),requestname,RequestListener,contentType,recordbool);
	}
	

	/***
	 * 获取完整请求网址
	 */
	  public static String getUrlString(String url, HttpRequestParams params) {
	        if(params != null) {
	            String paramString = params.getParamString(encoding);
	            if (url.indexOf("?") == -1) {
	                url += "?" + paramString;
	            } else {
	                url += "&" + paramString;
	            }
	        }

	        return url;
	    }
	  
	  /****
		 * 发送请求
		 * @param httpClient 
		 * @param httpContext
		 * @param uriRequest  
		 * @param httpparamname
		 * @param requestListener
		 * @param contentType
		 */
		private void sendRequest(DefaultHttpClient httpClient,
				HttpContext httpContext,  HttpUriRequest uriRequest, String requestname,
				HttpRequestListener requestListener,String contentType,boolean recordbool) {
			if(contentType!=null)
			{
				uriRequest.setHeader("Content-Type", contentType);
			}
			Log.e("url===>", uriRequest.getURI().toString());
			new Thread(new HttpRequest(httpClient, uriRequest, httpContext, requestname,headers, requestListener, encoding,recordbool)).start();
		}

		/***
		 * 返回post加入请求参数的连接
		 * @param requestBase
		 * @param entity
		 * @return
		 */
		  private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) {
		        if(entity != null){
		            requestBase.setEntity(entity);
		        }

		        return requestBase;
		    }
		  
		  /***
		   * 初始话下载管理器
		   * @param locationpath
		   * @param url
		   * @param thread_count
		   * @param context
		   * @param downloadListener
		   * @return
		   */
		  public Downloader getDownloader(String locationpath,String url,int thread_count,
		            Context context,DownloadListener downloadListener)
		  {
		      Downloader downloader=new Downloader(locationpath, url, thread_count, context, downloadListener);
		      new Thread(downloader).start();
		      return downloader;
		  }
		  
		  /**
		   * 设置标题与唯一标示
		   * @param downloader
		   * @param title
		   * @param id
		   */
		  public void setTitleid(Downloader downloader,String title,String id)
		  {
		      downloader.setTileid(title, id);
		  }
		  
		  /***
		   * 暂停文件下载
		   * @param downloader
		   */
		 public void PauseFile(Downloader downloader)
		 {
		     downloader.pause();
		 }
		 
		 /**
		  * 重新开始下载
		  * @param downloader
		  */
		 public void StartFile(Downloader downloader)
		 {
		     downloader.down();
		 }
		
}
